package com.lwy.qiuchao.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lwy.common.constant.SafetyBoxPrice;
import com.lwy.common.utils.R;
import com.lwy.qiuchao.order.dao.OrderDao;
import com.lwy.qiuchao.order.dao.OrderItemDao;
import com.lwy.qiuchao.order.entity.OrderItemEntity;
import com.lwy.qiuchao.order.feign.IntegrationServiceFeign;
import com.lwy.qiuchao.order.feign.WareServiceFeign;
import com.lwy.qiuchao.order.service.OrderService;
import com.lwy.qiuchao.order.vo.BoxOrderVo;
import com.lwy.qiuchao.order.vo.SkuDetailVo;
import com.lwy.qiuchao.order.vo.SubmitOrderVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.lwy.common.utils.PageUtils;
import com.lwy.common.utils.Query;

import com.lwy.qiuchao.order.entity.OrderEntity;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    @Autowired
    OrderDao orderDao;

    @Autowired
    OrderItemDao orderItemDao;

    @Autowired
    WareServiceFeign wareServiceFeign;

    @Autowired
    IntegrationServiceFeign integrationServiceFeign;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    // 贩卖机订单
    @Override
    public void confirmVendingOrder(SubmitOrderVo submitOrderVo) {

        //1、创建订单
        OrderEntity orderEntity = new OrderEntity();
        String orderSn = IdWorker.getTimeId();
        orderEntity.setMId(submitOrderVo.getMemberId());
        orderEntity.setOrderSn(orderSn);

        //2、订单类型 支付类型 订单状态
        orderEntity.setTypeInfo(2);
        orderEntity.setPayType(1);
        orderEntity.setStatus(0);

        // 1、用skuId去商品系统拿去商品价格
        List<SkuDetailVo> skuInfoVos = submitOrderVo.getSkuInfoVos();
        List<SkuDetailVo> skuInfos = skuInfoVos.stream().map(skuInfoVo -> {
            R r = wareServiceFeign.skuinfobyid(skuInfoVo.getSkuId());
            if (r.getcode() == 0) {
                SkuDetailVo skuDetailVo = r.getData(new TypeReference<SkuDetailVo>() {
                });
                skuInfoVo.setSkuName(skuDetailVo.getSkuName());
                skuInfoVo.setSkuImg(skuDetailVo.getSkuImg());
                skuInfoVo.setPrice(skuDetailVo.getPrice());
                skuInfoVo.setBrandName(skuDetailVo.getBrandName());
            }
            return skuInfoVo;
        }).collect(Collectors.toList());

        BigDecimal totalPrice = new BigDecimal("0");
        for (SkuDetailVo skuInfo : skuInfos) {
            BigDecimal skuPrice = skuInfo.getPrice().multiply(new BigDecimal(skuInfo.getSkuCount()));
            totalPrice = totalPrice.add(skuPrice);
        }

        //远程调用
        HashMap<String, Object> map = new HashMap<>();
        map.put("memberId", submitOrderVo.getMemberId());
        R r = integrationServiceFeign.getInteBymid(map);

        if (r.getcode() != 0) {
            throw new RuntimeException("积分调用失败");
        }

        Integer inteValue = r.getData(new TypeReference<Integer>() {});

        double inteValuePrice = inteValue / 10;

        BigDecimal inteValueDecimal = new BigDecimal(inteValuePrice);


        if (inteValueDecimal.compareTo(totalPrice) >= 0) {

            //应付价格
            orderEntity.setPayAmount(new BigDecimal("0"));

            // 积分
            orderEntity.setIntegration((totalPrice.multiply(new BigDecimal("10"))).intValue());

            //积分价格
            orderEntity.setIntergrationAmount(totalPrice);

        } else {
            //应付价格
            orderEntity.setPayAmount(totalPrice.subtract(inteValueDecimal));

            // 积分
            orderEntity.setIntegration(inteValue);

            //积分价格
            orderEntity.setIntergrationAmount(inteValueDecimal);
        }

        //总价
        orderEntity.setTotalAmount(totalPrice);

        // 时间
        orderEntity.setCreateTime(new Date());

        // 保存订单
        orderDao.insert(orderEntity);

        // 5、创建订单item
        saveOrderItemEntity(orderSn, skuInfos);


    }

    // 保存贩卖机订单item项
    private void saveOrderItemEntity(String orderSn, List<SkuDetailVo> skuInfos) {
        for (SkuDetailVo skuInfo : skuInfos) {
            OrderItemEntity orderItemEntity = new OrderItemEntity();
            OrderEntity order = orderDao.selectOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
            orderItemEntity.setOrderId(order.getOrderId());
            orderItemEntity.setOrderSn(order.getOrderSn());
            orderItemEntity.setSkuId(skuInfo.getSkuId());
            orderItemEntity.setSkuName(skuInfo.getSkuName());
            orderItemEntity.setSkuPrice(skuInfo.getPrice());
            orderItemEntity.setSkuQuantity(skuInfo.getSkuCount());
            // 6、保存订单item
            orderItemDao.insert(orderItemEntity);
        }
    }

    // 安全柜订单
    @Override
    public void confirmBoxOrder(BoxOrderVo boxOrderVo) {

        //1、创建订单
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setMId(boxOrderVo.getMemberId());
        String orderSn = IdWorker.getTimeId();
        orderEntity.setOrderSn(orderSn);

        //2、订单类型 支付类型 订单状态
        orderEntity.setTypeInfo(2);
        orderEntity.setPayType(1);
        orderEntity.setStatus(0);

        //3、计算价格
        Long useTime = boxOrderVo.getUseTime();
        double price = (int) (useTime / SafetyBoxPrice.TenMin) * SafetyBoxPrice.TEN_MIN_PRICE; // 十分钟单位价格
        BigDecimal payPrice = new BigDecimal(price);
        // 价格插入
        orderEntity.setTotalAmount(payPrice);
        orderEntity.setPayAmount(payPrice);
        orderEntity.setIntergrationAmount(new BigDecimal("0"));
        // 时间
        orderEntity.setCreateTime(new Date());

        // 4、保存订单
        orderDao.insert(orderEntity);

        // 5、创建订单item
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        OrderEntity order = orderDao.selectOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
        orderItemEntity.setOrderId(order.getOrderId());
        orderItemEntity.setOrderSn(order.getOrderSn());
        orderItemEntity.setSkuId(1L);
        orderItemEntity.setSkuName("安全柜");
        orderItemEntity.setSkuPrice(payPrice);
        orderItemEntity.setSkuQuantity(1);

        // 6、保存订单item
        orderItemDao.insert(orderItemEntity);
    }

}